/**
 * 测试用执行接口测试用例
 *
 * Created by snowingsea on 2020/03/15.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmarks = [require('./../../../benchmark/run-tests/self_designed')];

const files = require('./../../../../phoenix/models/files');
const tasks = require('./../../../../phoenix/models/tasks');

module.exports = describe('/PUT project-versions/:id/results.json', function () {
  const administrator = new Administrator();
  let project = {};
  const newUserIds = [];
  function url(versionId) {
    return `/project-versions/${versionId}/results.json`;
  }

  /**
   * 补全函数信息
   * @param {Object} tree 树结构
   * @return {Promise}
   */
  function completeFunctionLeaf(tree) {
    if (tree.kind === files.kind.directory) {
      const promises = tree.children.map((child) => completeFunctionLeaf(child));
      return Promise.all(promises);
    }
    return new Promise((resolve, reject) => {
      chai.request(uri)
        .get(`/files/${tree.fileId}/functions.json`)
        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
        .end((err, res) => {
          if (err) {
            reject(err);
            return;
          }
          if (res.body.functions.length !== 0) {
            tree.children = res.body.functions;
          }
          resolve();
        });
    });
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((res) => {
        project = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');

  // 正常发起请求
  benchmarks.forEach((benchmark) => {
    const extensions = benchmark.config.languages.c.suffixes
      .concat(benchmark.config.headers.suffixes);
    it(`it should run all tests of ${benchmark.name}`, function (done) {
      let projectVersion;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllTests(benchmark);
        })
        .then(() => project.creator.login())
        .then(() => {
          chai.request(uri)
            .put(url(projectVersion.versionId))
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseRun);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              let actualTree;
              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => projectVersion.rootDirectory.getTree(extensions))
                .then((res) => {
                  actualTree = res;
                  common.should.be.fileTreeMessage(actualTree);
                  return completeFunctionLeaf(actualTree.tree);
                })
                .then(() => {
                  actualTree.total.should.be.eql(benchmark.result.total);
                  common.should.be.equal.tree(actualTree.tree, benchmark.result.tree);
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 执行某个文件的测试用例
  benchmarks.forEach((benchmark) => {
    const extensions = benchmark.config.languages.c.suffixes
      .concat(benchmark.config.headers.suffixes);
    it(`it should run test of one file in ${benchmark.name}`, function (done) {
      let projectVersion;
      let fileId;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllTests(benchmark);
        })
        .then((res) => {
          fileId = res[0].function.fileId;
          return project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .put(url(projectVersion.versionId))
            .query({ fileIds: fileId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseRun);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              let actualTree;
              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => projectVersion.rootDirectory.getTree(extensions))
                .then((res) => {
                  actualTree = res;
                  common.should.be.fileTreeMessage(actualTree);
                  return completeFunctionLeaf(actualTree.tree);
                })
                .then(() => {
                  actualTree.total.should.be.eql(benchmark.result.total);
                  actualTree = actualTree.tree;
                  let expectedTree = benchmark.result.tree;
                  const actualRootArray = [actualTree];
                  while (actualRootArray.length > 0) {
                    const root = actualRootArray.pop();
                    if (root.fileId === fileId) {
                      actualTree = root;
                      break;
                    }
                    if (root.fileId && root.kind === files.kind.file) {
                      root.should.not.have.property('statementCoverage');
                      root.should.not.have.property('branchCoverage');
                      root.should.not.have.property('mcdcCoverage');
                    }
                    if (root.children) {
                      root.children.forEach((child) => {
                        actualRootArray.push(child);
                      });
                    }
                  }
                  const expectedRootArray = [expectedTree];
                  while (expectedRootArray.length > 0) {
                    const root = expectedRootArray.pop();
                    if (root.path === actualTree.path) {
                      expectedTree = root;
                      break;
                    }
                    if (root.children) {
                      root.children.forEach((child) => {
                        expectedRootArray.push(child);
                      });
                    }
                  }
                  common.should.be.equal.tree(actualTree, expectedTree);
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 执行某个函数的测试用例
  benchmarks.forEach((benchmark) => {
    const extensions = benchmark.config.languages.c.suffixes
      .concat(benchmark.config.headers.suffixes);
    it(`it should run tests of one function in ${benchmark.name}`, function (done) {
      let projectVersion;
      let functionId;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllTests(benchmark);
        })
        .then((res) => {
          functionId = res[0].function.functionId;
          return project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .put(url(projectVersion.versionId))
            .query({ functionIds: functionId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseRun);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              let actualTree;
              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => projectVersion.rootDirectory.getTree(extensions))
                .then((res) => {
                  actualTree = res;
                  common.should.be.fileTreeMessage(actualTree);
                  return completeFunctionLeaf(actualTree.tree);
                })
                .then(() => {
                  actualTree.total.should.be.eql(benchmark.result.total);
                  actualTree = actualTree.tree;
                  let expectedTree = benchmark.result.tree;
                  const actualRootArray = [actualTree];
                  while (actualRootArray.length > 0) {
                    const root = actualRootArray.pop();
                    if (root.functionId === functionId) {
                      actualTree = root;
                      break;
                    }
                    if (root.functionId) {
                      root.statementCoverage.should.be.eql(0);
                      root.branchCoverage.should.be.eql(0);
                    }
                    if (root.children) {
                      root.children.forEach((child) => {
                        actualRootArray.push(child);
                      });
                    }
                  }
                  const expectedRootArray = [expectedTree];
                  while (expectedRootArray.length > 0) {
                    const root = expectedRootArray.pop();
                    if (root.functionName === actualTree.functionName) {
                      expectedTree = root;
                      break;
                    }
                    if (root.children) {
                      root.children.forEach((child) => {
                        expectedRootArray.push(child);
                      });
                    }
                  }
                  common.should.be.equal.tree(actualTree, expectedTree);
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 没有测试用例可以执行
  benchmarks.forEach((benchmark) => {
    it(`it should fail when no test cases to run of ${benchmark.name}`, function (done) {
      let projectVersion;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllTests(benchmark);
        })
        .then(() => project.creator.login())
        .then(() => {
          chai.request(uri)
            .put(url(projectVersion.versionId))
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .query({ exceptFileIds: [projectVersion.rootDirectory.fileId] })
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可执行冻结项目的测试用例
  it('it should fail to run tests in frozen project', function (done) {
    let newProjectId;
    let newVersionId;
    project.creator.createRandomProject()
      .then((project) => {
        newProjectId = project.projectId;
        return project.createRandomVersion();
      })
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.creator.freezeProject(newProjectId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可生成冻结项目版本中的测试用例
  it('it should fail to generate tests in frozen project version', function (done) {
    let newVersionId;
    project.createRandomVersion()
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.freezeVersion(versionId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可执行他人项目的测试用例
  it('it should fail to run tests when the project is not yours', function (done) {
    let otherVersionId;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then(({ versionId }) => {
        otherVersionId = versionId;
        return project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .put(url(otherVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可执行不存在的项目文件的测试用例
  it('it should fail to run tests when the project is not exist', function (done) {
    let newProjectId;
    let newVersionId;
    project.creator.createRandomProject()
      .then((project) => {
        newProjectId = project.projectId;
        return project.createRandomVersion();
      })
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.creator.removeProject(newProjectId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
